package cn.lzy.study.datasource.aspect;

import cn.lzy.study.datasource.datasource.DataSourceType;
import cn.lzy.study.datasource.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

/**
 * 全局数据源切换切面（网页切换）
 * @author LZY
 * @since 2022-08-13
 */
@Component
@Aspect
// 设置优先级（执行顺序），数字越小，优先级越高
@Order(9)
public class GloalDataSourceAspect {

    @Autowired
    private HttpSession httpSession;

    // 拦截切点：所有service层的任意类任意方法
    @Pointcut("execution(* cn.lzy.study.datasource.service.*.*(..))")
    public void pc() {

    }


    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp) {

        // 从 session 中获取指定的数据源名称，并设置到 ContextHolder 中去
        DynamicDataSourceContextHolder.setDataSourceType((String) httpSession.getAttribute(DataSourceType.DS_SESSION_KEY));
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
        return null;
    }
}
